package trefliq.EJB.sessionbeans;

import java.util.List;
import javax.annotation.security.PermitAll;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import trefliq.EJB.entities.Account;

/**
 *
 * @author Eric
 */

@Stateless
@LocalBean
@PermitAll // (by default, allow all, restrict what's necessary)
public class AccountSession {
    
    @PersistenceContext(unitName="trefliqPU")
    private EntityManager em;

    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN})
    public List<Account> getAllAccounts() {
        return em.createNamedQuery("findAllAccounts", Account.class).getResultList();
    }
    
    public Account findAccount(Long accountId) {
        return em.createNamedQuery("findAccountById", Account.class).
                    setParameter("id", accountId).getSingleResult();
    }
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN})
    public Account deleteAccount(Account account) {
        
        em.remove(em.merge(account));
        return account;
    }
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
    public Account editAccount(Account account) {
        
        em.merge(account);
        return account;
    }
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
    public Account createAccount(Account account) {

        em.persist(account);
        
        return account;
    }
    
    // DB helper methods
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN})
    public void deleteAll() {
        Query q = em.createQuery("DELETE FROM Account a");
        q.executeUpdate();
    }
}
